import config from './api.mjs';
import { syncDocs } from './syncYuqueDocs.mjs';
import { getDocDetail } from './api.mjs';
import { getValidFileName, writeContent } from './syncYuqueDocs.mjs';
/**
 * 给语雀文档添加frontmatter
 * @param {string} title 文章标题
 * @param {string} date 创建日期
 * @param {string} lastmod 修改日期
 * @param {string} slug 末尾url
 * @param {string} content 文章内容
 * @returns {string} 处理后的文章内容
 */

let defaultFrontmatter = '';
const frontmatter = config.frontmatter || {};
for (let key of Object.keys(frontmatter)) {
  defaultFrontmatter += `${key}: ${frontmatter[key]}\n`;
}
export function addFrontmatter(
  content = '',
  title,
  date,
  lastmod,
  slug,
  cover
) {
  const reg = /^(.*?)(?:---|$)/s;
  const found = content.match(reg);
  let substr = '';
  let len = 0;
  let customFrontmatter = '';
  if (found) {
    substr = found[1].replace(/<br \/>/g, '\n');
    // 校验是否是yaml语法
    const regex = /^(\s*\w+:.+)+/;
    const keyValues = substr.match(regex);
    if (keyValues) {
      // 将字符串转换为yaml字符串
      customFrontmatter = dealYuqueFrontmatter(keyValues[0]);
      len = found[0].length;
    }
  }
  title.replace(/"/g, "'");
  title = `title: "${title}"`;
  date = `date: ${date}`;
  lastmod = `lastmod: ${lastmod}`;
  slug = `slug: ${slug}`;
  cover = `cover: ${cover}`;
  let frontmatter = `---\n${title}\n${date}\n${lastmod}\n${slug}\n${cover}\n${defaultFrontmatter}\n${customFrontmatter}\n---`;
  return `${frontmatter}\n${content.slice(len)}`;
}

const arrKeyName = ['categories', 'tags'];
function dealYuqueFrontmatter(frontmatter) {
  const lines = frontmatter.split('\n').filter((item) => item.trim() != '');
  const arr = [];
  for (let line of lines) {
    const index = line.indexOf(':');
    let key = line.slice(0, index);
    let value = line.slice(index + 1).trim();
    if (arrKeyName.includes(key)) {
      value = toYamlArray(value);
    }
    arr.push(`${key}: ${value}`);
  }
  return arr.join('\n');
}
function toYamlArray(str = '') {
  const reg = new RegExp(`[${config.frontmatterSplit || '，,;；'}]+`);
  const arr = str.split(reg);
  return `\n- ${arr.join('\n- ')}`;
}

/**
 * 同步单个语雀文档并添加frontmatter
 * @param {string} namespace 语雀文档的命名空间 login/repo
 * @param {string} slug 文章slug，具体见网页版语雀文档链接最后一部分
 * @param {string} filename 文章标题，用于输出文件的名称
 * @param {string} contentOutputDir 输出目录
 */
export async function syncDocWithFrontmatter(
  namespace,
  slug,
  filename,
  contentOutputDir
) {
  filename = getValidFileName(filename);
  const res = await getDocDetail(namespace, slug);
  // 内容输出路径，没有配置默认根目录下的content文件夹
  let output = contentOutputDir || `${__dirname}/content`;
  // 文件命名采取标题-slug形式
  output = `${output}/${filename}.md`;
  // 给内容添加frontmatter
  const { title, created_at, updated_at, body, cover, first_published_at } =
    res.data;
  const content = addFrontmatter(
    body,
    title,
    first_published_at,
    updated_at,
    slug,
    cover
  );
  await writeContent(output, content);
}
/**
 * 导出所有知识库下的文档
 * @param {string} login 语雀用户login
 * @param {string} repo 知识库slug
 * @param {string} cacheDir 缓存目录
 * @param {string} contentOutputDir 内容输出目录
 */
export async function syncYuqueWithFrontmatter(
  login,
  repo,
  cacheDir,
  contentOutputDir
) {
  console.log('开始同步带有frontmatter的文档');
  await syncDocs(
    syncDocWithFrontmatter,
    login,
    repo,
    cacheDir,
    contentOutputDir
  );
}
